//package com.software.graduationproject.commons.filter;
//
//import com.software.graduationproject.commons.enums.ResultCodes;
//import com.software.graduationproject.commons.util.JwtUtil;
//
//import com.software.graduationproject.modules.sys.entity.LoginUser;
//import com.software.graduationproject.commons.redis.RedisCache;
//import io.jsonwebtoken.Claims;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import javax.servlet.FilterChain;
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.Objects;
//
///**
// * 认证权限过滤器
// */
//@Component
//public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
//
//    @Autowired
//    private RedisCache redisCache;
//
//    @Override
//    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//        // 获取token
//        String authorization = httpServletRequest.getHeader("authorization");
//        if (!StringUtils.hasText(authorization)) {
//            // 放行
//            filterChain.doFilter(httpServletRequest, httpServletResponse);
//            return;
//        }
//        // 解析token
//        String userId;
//        try {
//            Claims claims = JwtUtil.parseJWT(authorization);
//            userId = claims.getSubject();
//        } catch (Exception e) {
//            throw new ServletException(ResultCodes.FAILURE_AUTHORIZE_EXPIRED.getMessage());
//        }
//        // 从Redis中获取用户信息
//        String redisKey = "login:" + userId;
//        LoginUser loginUser = redisCache.getCacheObject(redisKey);
//        if (Objects.isNull(loginUser)) {
//            throw new ServletException("用户未登录");
//        }
//        // 存入SecurityContextHolder
//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        //放行
//        filterChain.doFilter(httpServletRequest, httpServletResponse);
//    }
//}
